package server.jdbcdao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import server.core.Right;
import server.core.User;
import server.dao.UserRightDAO;
import server.idatasource.DataSourceFactory;
import server.idatasource.IUserRightDataSource;

public class UserRightJdbcDAO implements UserRightDAO {

	/*Returns all rights of the given user in a list. If an error occurs, in the first elements username field 
	 * is returned "ERROR".*/
	@Override
	public List<Right> getAllRightsByUser(User user) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserRightDataSource userRightData = ds.getUserRightDataSource();

		List<List<String>> result = userRightData.getAllRightsByUser(user.getUsername());
		Iterator<List<String>> it1 = result.iterator();
		Right right;
		List<Right> rightList = new ArrayList<Right>();

		while (it1.hasNext()) {
			Iterator<String> it2 = it1.next().iterator();
			right = new Right();
			right.setId(Integer.parseInt(it2.next()));
			right.setName(it2.next());
			rightList.add(right);
		}
		return rightList;

	}

	/*Inserts a new right to a specified user given in the argument, into the database. Returns a string, with the
	 * value "OK" if the operation was successful, else returns "ERROR".*/
	@Override
	public String insertUserRight(User user, Right right) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserRightDataSource userRightData = ds.getUserRightDataSource();

		return userRightData.insertUserRight(user.getUsername(), right.getId());
	}

	@Override
	/*Deletes a userRight from database, having the username and rightID given as argument. Returns a string, with the
	 * value "OK" if the operation was successful, else returns "ERROR".*/
	public String deleteUserRight(User user, Right right) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserRightDataSource userRightData = ds.getUserRightDataSource();

		return userRightData.deleteUserRight(user.getUsername(), right.getId());
	}

}
